class PopupManager {
  constructor() {
    this.currentTab = null;
    this.currentUrl = '';
    this.rules = { urlRules: [] };
    this.selectedUrlRuleId = '';
    this.editingUrlRule = null;
    this.editingElementRule = null;
    this.init();
  }

  async init() {
    try {
      this.showLoading(true);
      await this.getCurrentTab();
      await this.loadRules();
      this.setupEventListeners();
      this.updateUI();
    } catch (error) {
      console.error('Failed to initialize popup:', error);
      this.showToast('Failed to initialize', 'error');
    } finally {
      this.showLoading(false);
    }
  }

  async getCurrentTab() {
    try {
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      this.currentTab = tab;
      this.currentUrl = tab.url;
      document.getElementById('currentUrl').textContent = this.currentUrl;
    } catch (error) {
      console.error('Failed to get current tab:', error);
      this.currentUrl = '';
    }
  }

  async loadRules() {
    try {
      this.rules = await StorageManager.getRules();
      this.updateMatchStatus();
    } catch (error) {
      console.error('Failed to load rules:', error);
      this.rules = { urlRules: [] };
    }
  }

  setupEventListeners() {
    // Tab switching
    document.querySelectorAll('.tab-button').forEach(button => {
      button.addEventListener('click', (e) => {
        this.switchTab(e.target.dataset.tab);
      });
    });

    // URL Rules
    document.getElementById('addUrlRule').addEventListener('click', () => {
      this.openUrlRuleModal();
    });

    // Element Rules
    document.getElementById('urlSelector').addEventListener('change', (e) => {
      this.selectedUrlRuleId = e.target.value;
      this.updateElementRulesTable();
      document.getElementById('addElementRule').disabled = !this.selectedUrlRuleId;
    });

    document.getElementById('addElementRule').addEventListener('click', () => {
      this.openElementRuleModal();
    });

    // Modals
    this.setupModalEventListeners();

    // Storage changes
    StorageManager.onChanged((newRules) => {
      this.rules = newRules || { urlRules: [] };
      this.updateUI();
    });

    // 添加事件委托处理表格按钮点击
    this.setupTableEventDelegation();
  }

  setupTableEventDelegation() {
    // URL规则表格事件委托
    document.getElementById('urlRulesBody').addEventListener('click', (e) => {
      if (e.target.tagName === 'BUTTON') {
        const action = e.target.getAttribute('data-action');
        const ruleId = e.target.getAttribute('data-rule-id');
        
        switch (action) {
          case 'edit':
            this.editUrlRule(ruleId);
            break;
          case 'toggle':
            this.toggleUrlRule(ruleId);
            break;
          case 'delete':
            this.deleteUrlRule(ruleId);
            break;
        }
      }
    });

    // Element规则表格事件委托
    document.getElementById('elementRulesBody').addEventListener('click', (e) => {
      if (e.target.tagName === 'BUTTON') {
        const action = e.target.getAttribute('data-action');
        const elementId = e.target.getAttribute('data-element-id');
        const urlId = e.target.getAttribute('data-url-id');
        
        switch (action) {
          case 'test':
            this.testElementRule(elementId, urlId);
            break;
          case 'edit':
            this.editElementRule(elementId, urlId);
            break;
          case 'toggle':
            this.toggleElementRule(elementId, urlId);
            break;
          case 'delete':
            this.deleteElementRule(elementId, urlId);
            break;
        }
      }
    });
  }

  setupModalEventListeners() {
    // URL Rule Modal
    document.getElementById('closeUrlModal').addEventListener('click', () => {
      this.closeModal('urlRuleModal');
    });

    document.getElementById('cancelUrlRule').addEventListener('click', () => {
      this.closeModal('urlRuleModal');
    });

    document.getElementById('saveUrlRule').addEventListener('click', () => {
      this.saveUrlRule();
    });

    document.getElementById('urlPattern').addEventListener('input', (e) => {
      this.validateUrlPattern(e.target.value);
      this.generatePatternSuggestions(e.target.value);
    });

    document.getElementById('testUrlPattern').addEventListener('click', () => {
      const pattern = document.getElementById('urlPattern').value.trim();
      if (pattern) {
        this.validateUrlPattern(pattern);
      } else {
        this.showValidation('urlValidation', '请输入URL模式', 'error');
      }
    });

    // Element Rule Modal
    document.getElementById('closeElementModal').addEventListener('click', () => {
      this.closeModal('elementRuleModal');
    });

    document.getElementById('cancelElementRule').addEventListener('click', () => {
      this.closeModal('elementRuleModal');
    });

    document.getElementById('saveElementRule').addEventListener('click', () => {
      this.saveElementRule();
    });

    document.getElementById('elementSelector').addEventListener('input', (e) => {
      this.validateElementSelector(e.target.value);
    });

    document.getElementById('testSelector').addEventListener('click', () => {
      this.testElementSelector();
    });

    document.getElementById('highlightElements').addEventListener('click', () => {
      this.highlightElements();
    });

    // Confirmation Modal
    document.getElementById('closeConfirmModal').addEventListener('click', () => {
      this.closeModal('confirmModal');
    });

    document.getElementById('cancelConfirm').addEventListener('click', () => {
      this.closeModal('confirmModal');
    });

    // Close modals on backdrop click
    document.querySelectorAll('.modal').forEach(modal => {
      modal.addEventListener('click', (e) => {
        if (e.target === modal) {
          this.closeModal(modal.id);
        }
      });
    });
  }

  switchTab(tabName) {
    // Update tab buttons
    document.querySelectorAll('.tab-button').forEach(btn => {
      btn.classList.toggle('active', btn.dataset.tab === tabName);
    });

    // Update tab content
    document.querySelectorAll('.tab-content').forEach(content => {
      content.classList.toggle('active', content.id === tabName);
    });

    // Update tables based on active tab
    if (tabName === 'url-rules') {
      this.updateUrlRulesTable();
    } else if (tabName === 'element-rules') {
      this.updateUrlSelector();
      this.updateElementRulesTable();
    }
  }

  updateUI() {
    this.updateUrlRulesTable();
    this.updateUrlSelector();
    this.updateElementRulesTable();
    this.updateStats();
    this.updateMatchStatus();
  }

  updateUrlRulesTable() {
    const tbody = document.getElementById('urlRulesBody');
    const emptyState = document.getElementById('urlRulesEmpty');
    
    tbody.innerHTML = '';
    
    if (!this.rules.urlRules || this.rules.urlRules.length === 0) {
      emptyState.classList.add('show');
      return;
    }
    
    emptyState.classList.remove('show');
    
    this.rules.urlRules.forEach(rule => {
      const row = this.createUrlRuleRow(rule);
      tbody.appendChild(row);
    });
  }

  createUrlRuleRow(rule) {
    const row = document.createElement('tr');
    const elementCount = rule.elementRules ? rule.elementRules.length : 0;
    
    console.log(`Creating row for rule: ${rule.pattern}, current URL: ${this.currentUrl}`);
    const isMatching = URLMatcher.isMatch(this.currentUrl, rule.pattern);
    console.log(`Rule "${rule.pattern}" matching result: ${isMatching}`);
    
    row.innerHTML = `
      <td class="pattern-cell" title="${rule.pattern}">${rule.pattern}</td>
      <td>
        <span class="status-badge ${rule.enabled ? 'status-enabled' : 'status-disabled'}">
          ${rule.enabled ? '已启用' : '已禁用'}
        </span>
        ${isMatching ? '<span style="margin-left: 8px; color: #4caf50; font-size: 16px;" title="匹配当前页面">●</span>' : '<span style="margin-left: 8px; color: #ccc; font-size: 16px;" title="不匹配当前页面">○</span>'}
      </td>
      <td class="matches-count ${elementCount === 0 ? 'zero' : ''}">${elementCount}</td>
      <td>
        <div class="table-actions">
          <button class="btn btn-small btn-secondary" data-action="edit" data-rule-id="${rule.id}">
            编辑
          </button>
          <button class="btn btn-small btn-secondary" data-action="toggle" data-rule-id="${rule.id}">
            ${rule.enabled ? '禁用' : '启用'}
          </button>
          <button class="btn btn-small btn-danger" data-action="delete" data-rule-id="${rule.id}">
            删除
          </button>
        </div>
      </td>
    `;
    
    return row;
  }

  updateUrlSelector() {
    const selector = document.getElementById('urlSelector');
    selector.innerHTML = '<option value="">选择网址规则...</option>';
    
    if (this.rules.urlRules) {
      this.rules.urlRules.forEach(rule => {
        const option = document.createElement('option');
        option.value = rule.id;
        option.textContent = rule.pattern;
        if (rule.id === this.selectedUrlRuleId) {
          option.selected = true;
        }
        selector.appendChild(option);
      });
    }
  }

  updateElementRulesTable() {
    const tbody = document.getElementById('elementRulesBody');
    const emptyState = document.getElementById('elementRulesEmpty');
    
    tbody.innerHTML = '';
    
    const urlRule = this.rules.urlRules?.find(rule => rule.id === this.selectedUrlRuleId);
    const elementRules = urlRule?.elementRules || [];
    
    if (elementRules.length === 0) {
      emptyState.classList.add('show');
      return;
    }
    
    emptyState.classList.remove('show');
    
    elementRules.forEach(elementRule => {
      const row = this.createElementRuleRow(elementRule, urlRule.id);
      tbody.appendChild(row);
    });
  }

  createElementRuleRow(elementRule, urlRuleId) {
    const row = document.createElement('tr');
    
    row.innerHTML = `
      <td class="selector-cell" title="${elementRule.selector}">${elementRule.selector}</td>
      <td>
        <span class="action-badge action-${elementRule.action}">
          ${elementRule.action === 'hide' ? '隐藏' : '显示'}
        </span>
      </td>
      <td class="matches-count">-</td>
      <td>
        <span class="status-badge ${elementRule.enabled ? 'status-enabled' : 'status-disabled'}">
          ${elementRule.enabled ? '已启用' : '已禁用'}
        </span>
      </td>
      <td>
        <div class="table-actions">
          <button class="btn btn-small btn-secondary" data-action="test" data-element-id="${elementRule.id}" data-url-id="${urlRuleId}">
            测试
          </button>
          <button class="btn btn-small btn-secondary" data-action="edit" data-element-id="${elementRule.id}" data-url-id="${urlRuleId}">
            编辑
          </button>
          <button class="btn btn-small btn-secondary" data-action="toggle" data-element-id="${elementRule.id}" data-url-id="${urlRuleId}">
            ${elementRule.enabled ? '禁用' : '启用'}
          </button>
          <button class="btn btn-small btn-danger" data-action="delete" data-element-id="${elementRule.id}" data-url-id="${urlRuleId}">
            删除
          </button>
        </div>
      </td>
    `;
    
    return row;
  }

  updateStats() {
    const totalUrlRules = this.rules.urlRules?.length || 0;
    const totalElementRules = this.rules.urlRules?.reduce((sum, rule) => {
      return sum + (rule.elementRules?.length || 0);
    }, 0) || 0;
    
    console.log(`Popup: Checking ${totalUrlRules} URL rules against ${this.currentUrl}`);
    
    const activeRules = this.rules.urlRules?.filter(rule => {
      if (!rule.enabled) {
        console.log(`Popup: Rule "${rule.pattern}" is disabled`);
        return false;
      }
      
      const matches = URLMatcher.isMatch(this.currentUrl, rule.pattern);
      console.log(`Popup: Rule "${rule.pattern}" ${matches ? 'MATCHES' : 'does not match'} current URL`);
      return matches;
    }).length || 0;
    
    console.log(`Popup: Found ${activeRules} active rules`);
    
    document.getElementById('totalUrlRules').textContent = totalUrlRules;
    document.getElementById('totalElementRules').textContent = totalElementRules;
    document.getElementById('activeRules').textContent = activeRules;
  }

  updateMatchStatus() {
    const matchingRules = URLMatcher.getMatchingRules(this.currentUrl, this.rules);
    const statusElement = document.getElementById('matchStatus');
    
    if (matchingRules.length > 0) {
      statusElement.textContent = `${matchingRules.length} 个规则活跃`;
      statusElement.classList.add('active');
    } else {
      statusElement.textContent = '无匹配规则';
      statusElement.classList.remove('active');
    }
  }

  // URL Rule Actions
  openUrlRuleModal(rule = null) {
    this.editingUrlRule = rule;
    const modal = document.getElementById('urlRuleModal');
    const title = document.getElementById('urlModalTitle');
    const pattern = document.getElementById('urlPattern');
    const enabled = document.getElementById('urlRuleEnabled');
    
    if (rule) {
      title.textContent = '编辑网址规则';
      pattern.value = rule.pattern;
      enabled.checked = rule.enabled;
    } else {
      title.textContent = '添加网址规则';
      pattern.value = '';
      enabled.checked = true;
      this.generatePatternSuggestions('');
    }
    
    this.clearValidation('urlValidation');
    this.showModal('urlRuleModal');
    pattern.focus();
  }

  async saveUrlRule() {
    const pattern = document.getElementById('urlPattern').value.trim();
    const enabled = document.getElementById('urlRuleEnabled').checked;
    
    if (!pattern) {
      this.showValidation('urlValidation', '模式不能为空', 'error');
      return;
    }
    
    const validation = URLMatcher.validatePattern(pattern);
    if (!validation.valid) {
      this.showValidation('urlValidation', validation.error, 'error');
      return;
    }
    
    try {
      this.showLoading(true);
      
      if (this.editingUrlRule) {
        await StorageManager.updateUrlRule(this.editingUrlRule.id, { pattern, enabled });
        this.showToast('网址规则已更新', 'success');
      } else {
        await StorageManager.addUrlRule(pattern);
        this.showToast('网址规则已添加', 'success');
      }
      
      await this.loadRules();
      this.updateUI();
      this.closeModal('urlRuleModal');
    } catch (error) {
      console.error('Failed to save URL rule:', error);
      this.showToast('保存规则失败', 'error');
    } finally {
      this.showLoading(false);
    }
  }

  async editUrlRule(ruleId) {
    const rule = this.rules.urlRules?.find(r => r.id === ruleId);
    if (rule) {
      this.openUrlRuleModal(rule);
    }
  }

  async toggleUrlRule(ruleId) {
    try {
      const rule = this.rules.urlRules?.find(r => r.id === ruleId);
      if (rule) {
        await StorageManager.updateUrlRule(ruleId, { enabled: !rule.enabled });
        await this.loadRules();
        this.updateUI();
        this.showToast(`规则已${rule.enabled ? '禁用' : '启用'}`, 'success');
      }
    } catch (error) {
      console.error('Failed to toggle URL rule:', error);
      this.showToast('切换规则状态失败', 'error');
    }
  }

  async deleteUrlRule(ruleId) {
    const rule = this.rules.urlRules?.find(r => r.id === ruleId);
    if (!rule) return;
    
    this.showConfirmation(
      'Delete URL Rule',
      `Are you sure you want to delete the rule "${rule.pattern}"? This will also delete all associated element rules.`,
      async () => {
        try {
          await StorageManager.deleteUrlRule(ruleId);
          await this.loadRules();
          this.updateUI();
          this.showToast('URL rule deleted', 'success');
        } catch (error) {
          console.error('Failed to delete URL rule:', error);
          this.showToast('Failed to delete rule', 'error');
        }
      }
    );
  }

  // Element Rule Actions
  openElementRuleModal(elementRule = null, urlRuleId = null) {
    if (!urlRuleId) {
      urlRuleId = this.selectedUrlRuleId;
    }
    
    if (!urlRuleId) {
      this.showToast('Please select a URL rule first', 'warning');
      return;
    }
    
    this.editingElementRule = elementRule;
    const modal = document.getElementById('elementRuleModal');
    const title = document.getElementById('elementModalTitle');
    const selector = document.getElementById('elementSelector');
    const action = document.getElementById('elementAction');
    const enabled = document.getElementById('elementRuleEnabled');
    
    if (elementRule) {
      title.textContent = 'Edit Element Rule';
      selector.value = elementRule.selector;
      action.value = elementRule.action;
      enabled.checked = elementRule.enabled;
    } else {
      title.textContent = 'Add Element Rule';
      selector.value = '';
      action.value = 'hide';
      enabled.checked = true;
    }
    
    this.clearValidation('elementValidation');
    this.showModal('elementRuleModal');
    selector.focus();
  }

  async saveElementRule() {
    const selector = document.getElementById('elementSelector').value.trim();
    const action = document.getElementById('elementAction').value;
    const enabled = document.getElementById('elementRuleEnabled').checked;
    
    if (!selector) {
      this.showValidation('elementValidation', 'Selector is required', 'error');
      return;
    }
    
    try {
      this.showLoading(true);
      
      if (this.editingElementRule) {
        await StorageManager.updateElementRule(
          this.selectedUrlRuleId,
          this.editingElementRule.id,
          { selector, action, enabled }
        );
        this.showToast('Element rule updated', 'success');
      } else {
        await StorageManager.addElementRule(this.selectedUrlRuleId, selector, action);
        this.showToast('Element rule added', 'success');
      }
      
      await this.loadRules();
      this.updateUI();
      this.closeModal('elementRuleModal');
    } catch (error) {
      console.error('Failed to save element rule:', error);
      this.showToast('Failed to save rule', 'error');
    } finally {
      this.showLoading(false);
    }
  }

  async editElementRule(elementRuleId, urlRuleId) {
    const urlRule = this.rules.urlRules?.find(r => r.id === urlRuleId);
    const elementRule = urlRule?.elementRules?.find(r => r.id === elementRuleId);
    if (elementRule) {
      this.selectedUrlRuleId = urlRuleId;
      this.openElementRuleModal(elementRule, urlRuleId);
    }
  }

  async toggleElementRule(elementRuleId, urlRuleId) {
    try {
      const urlRule = this.rules.urlRules?.find(r => r.id === urlRuleId);
      const elementRule = urlRule?.elementRules?.find(r => r.id === elementRuleId);
      if (elementRule) {
        await StorageManager.updateElementRule(
          urlRuleId,
          elementRuleId,
          { enabled: !elementRule.enabled }
        );
        await this.loadRules();
        this.updateUI();
        this.showToast(`Rule ${elementRule.enabled ? 'disabled' : 'enabled'}`, 'success');
      }
    } catch (error) {
      console.error('Failed to toggle element rule:', error);
      this.showToast('Failed to toggle rule', 'error');
    }
  }

  async deleteElementRule(elementRuleId, urlRuleId) {
    const urlRule = this.rules.urlRules?.find(r => r.id === urlRuleId);
    const elementRule = urlRule?.elementRules?.find(r => r.id === elementRuleId);
    if (!elementRule) return;
    
    this.showConfirmation(
      'Delete Element Rule',
      `Are you sure you want to delete the rule "${elementRule.selector}"?`,
      async () => {
        try {
          await StorageManager.deleteElementRule(urlRuleId, elementRuleId);
          await this.loadRules();
          this.updateUI();
          this.showToast('Element rule deleted', 'success');
        } catch (error) {
          console.error('Failed to delete element rule:', error);
          this.showToast('Failed to delete rule', 'error');
        }
      }
    );
  }

  async testElementRule(elementRuleId, urlRuleId) {
    const urlRule = this.rules.urlRules?.find(r => r.id === urlRuleId);
    const elementRule = urlRule?.elementRules?.find(r => r.id === elementRuleId);
    if (!elementRule) return;
    
    await this.testSelector(elementRule.selector);
  }

  // Validation and Testing
  validateUrlPattern(pattern) {
    if (!pattern) {
      this.clearValidation('urlValidation');
      return;
    }
    
    console.log(`Validating URL pattern: "${pattern}" against "${this.currentUrl}"`);
    
    const validation = URLMatcher.validatePattern(pattern);
    if (validation.valid) {
      const isMatching = URLMatcher.isMatch(this.currentUrl, pattern);
      console.log(`Pattern validation result: ${isMatching}`);
      
      this.showValidation(
        'urlValidation',
        isMatching ? `模式匹配当前页面: ${this.currentUrl}` : `模式不匹配当前页面: ${this.currentUrl}`,
        isMatching ? 'success' : 'warning'
      );
    } else {
      console.log(`Pattern validation failed: ${validation.error}`);
      this.showValidation('urlValidation', validation.error, 'error');
    }
  }

  generatePatternSuggestions(currentPattern) {
    const suggestionsContainer = document.getElementById('patternSuggestions');
    
    if (!this.currentUrl || currentPattern) {
      suggestionsContainer.classList.remove('show');
      return;
    }
    
    const suggestions = URLMatcher.suggestPatterns(this.currentUrl);
    
    if (suggestions.length === 0) {
      suggestionsContainer.classList.remove('show');
      return;
    }
    
    suggestionsContainer.innerHTML = '';
    suggestions.forEach(suggestion => {
      const item = document.createElement('div');
      item.className = 'suggestion-item';
      item.innerHTML = `
        <div class="suggestion-pattern">${suggestion.pattern}</div>
        <div class="suggestion-description">${suggestion.description}</div>
      `;
      item.addEventListener('click', () => {
        document.getElementById('urlPattern').value = suggestion.pattern;
        this.validateUrlPattern(suggestion.pattern);
        suggestionsContainer.classList.remove('show');
      });
      suggestionsContainer.appendChild(item);
    });
    
    suggestionsContainer.classList.add('show');
  }

  async validateElementSelector(selector) {
    if (!selector) {
      this.clearValidation('elementValidation');
      return;
    }
    
    try {
      const result = await this.sendMessageToTab({
        action: 'testSelector',
        selector: selector
      });
      
      if (result && result.valid) {
        this.showValidation(
          'elementValidation',
          `Found ${result.count} element${result.count !== 1 ? 's' : ''}`,
          result.count > 0 ? 'success' : 'warning'
        );
      } else {
        this.showValidation('elementValidation', result?.error || 'Invalid selector', 'error');
      }
    } catch (error) {
      this.showValidation('elementValidation', 'Cannot test selector on this page', 'warning');
    }
  }

  async testElementSelector() {
    const selector = document.getElementById('elementSelector').value.trim();
    if (!selector) {
      this.showToast('请输入选择器', 'warning');
      return;
    }
    
    // 首先ping content script确保它存在
    try {
      await this.sendMessageToTab({ action: 'ping' });
    } catch (pingError) {
      this.showToast('无法连接到页面脚本，请刷新页面', 'error');
      return;
    }
    
    // 测试选择器
    await this.testSelector(selector);
    
    // 同时测试隐藏功能
    try {
      console.log('Popup: Sending forceApplyRule message...');
      const result = await this.sendMessageToTab({
        action: 'forceApplyRule',
        rule: {
          id: 'test_rule',
          selector: selector,
          action: 'hide'
        }
      });
      
      if (result && result.success) {
        console.log('Force apply test result:', result);
        this.showToast(`强制应用测试成功，影响了 ${result.appliedCount} 个元素`, 'success');
      } else {
        console.error('Force apply test failed:', result);
        this.showToast('强制应用测试失败: ' + (result?.error || '未知错误'), 'error');
      }
    } catch (error) {
      console.error('Force apply test error:', error);
    }
  }

  async testSelector(selector) {
    try {
      const result = await this.sendMessageToTab({
        action: 'testSelector',
        selector: selector
      });
      
      if (result && result.valid) {
        this.showToast(`找到 ${result.count} 个元素`, 'info');
        
        // 额外的调试信息
        console.log('Element Controller Test Result:', result);
      } else {
        this.showToast(result?.error || '无效的选择器', 'error');
      }
    } catch (error) {
      console.error('Test selector error:', error);
      this.showToast('无法在此页面测试选择器', 'warning');
    }
  }

  async highlightElements() {
    const selector = document.getElementById('elementSelector').value.trim();
    if (!selector) {
      this.showToast('请输入选择器', 'warning');
      return;
    }
    
    try {
      const result = await this.sendMessageToTab({
        action: 'highlightElements',
        selector: selector
      });
      
      if (result && result.count > 0) {
        this.showToast(`Highlighted ${result.count} element${result.count !== 1 ? 's' : ''}`, 'success');
      } else {
        this.showToast('No elements found to highlight', 'warning');
      }
    } catch (error) {
      this.showToast('Cannot highlight elements on this page', 'warning');
    }
  }

  // Utility Methods
  async sendMessageToTab(message) {
    try {
      if (!this.currentTab?.id) {
        throw new Error('No active tab');
      }
      
      return await chrome.tabs.sendMessage(this.currentTab.id, message);
    } catch (error) {
      console.error('Popup: Failed to send message to tab:', error);
      throw error;
    }
  }

  showModal(modalId) {
    document.getElementById(modalId).classList.add('show');
  }

  closeModal(modalId) {
    document.getElementById(modalId).classList.remove('show');
  }

  showConfirmation(title, message, onConfirm) {
    document.getElementById('confirmTitle').textContent = title;
    document.getElementById('confirmMessage').textContent = message;
    
    const confirmButton = document.getElementById('confirmAction');
    confirmButton.onclick = () => {
      this.closeModal('confirmModal');
      onConfirm();
    };
    
    this.showModal('confirmModal');
  }

  showValidation(elementId, message, type) {
    const element = document.getElementById(elementId);
    element.textContent = message;
    element.className = `validation-status show ${type}`;
  }

  clearValidation(elementId) {
    const element = document.getElementById(elementId);
    element.classList.remove('show');
  }

  showLoading(show) {
    const overlay = document.getElementById('loadingOverlay');
    overlay.classList.toggle('show', show);
  }

  showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.textContent = message;
    
    container.appendChild(toast);
    
    // Trigger animation
    setTimeout(() => toast.classList.add('show'), 100);
    
    // Remove after 3 seconds
    setTimeout(() => {
      toast.classList.remove('show');
      setTimeout(() => {
        if (toast.parentNode) {
          toast.parentNode.removeChild(toast);
        }
      }, 300);
    }, 3000);
  }
}

// Initialize popup when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
  window.popupManager = new PopupManager();
});